import axios from '@ohos/axios'
import { Constants } from '../utils/Constants'

/**
 * API服务类
 */
export class ApiService {
  private static instance: ApiService
  private baseURL: string = Constants.API_BASE_URL
  private timeout: number = 10000

  private constructor() {
    this.setupInterceptors()
  }

  /**
   * 获取单例实例
   */
  static getInstance(): ApiService {
    if (!this.instance) {
      this.instance = new ApiService()
    }
    return this.instance
  }

  /**
   * 设置拦截器
   */
  private setupInterceptors() {
    // 请求拦截器
    axios.interceptors.request.use(
      (config) => {
        // 添加token到请求头
        // const token = StorageUtil.getToken()
        // if (token) {
        //   config.headers.Authorization = `Bearer ${token}`
        // }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )

    // 响应拦截器
    axios.interceptors.response.use(
      (response) => {
        return response
      },
      (error) => {
        this.handleError(error)
        return Promise.reject(error)
      }
    )
  }

  /**
   * 处理错误
   */
  private handleError(error: any) {
    if (error.response) {
      // 服务器响应错误
      const status = error.response.status
      switch (status) {
        case 401:
          console.error('未授权，请重新登录')
          break
        case 403:
          console.error('权限不足')
          break
        case 404:
          console.error('请求的资源不存在')
          break
        case 500:
          console.error('服务器内部错误')
          break
        default:
          console.error(`服务器错误：${status}`)
      }
    } else if (error.request) {
      // 请求发送失败
      console.error('网络错误，请检查网络连接')
    } else {
      // 其他错误
      console.error('请求配置错误')
    }
  }

  /**
   * GET请求
   */
  async get(url: string, params?: any): Promise<any> {
    try {
      const response = await axios.get(this.baseURL + url, {
        params,
        timeout: this.timeout
      })
      return response.data
    } catch (error) {
      throw error
    }
  }

  /**
   * POST请求
   */
  async post(url: string, data?: any): Promise<any> {
    try {
      const response = await axios.post(this.baseURL + url, data, {
        timeout: this.timeout
      })
      return response.data
    } catch (error) {
      throw error
    }
  }

  /**
   * PUT请求
   */
  async put(url: string, data?: any): Promise<any> {
    try {
      const response = await axios.put(this.baseURL + url, data, {
        timeout: this.timeout
      })
      return response.data
    } catch (error) {
      throw error
    }
  }

  /**
   * DELETE请求
   */
  async delete(url: string, params?: any): Promise<any> {
    try {
      const response = await axios.delete(this.baseURL + url, {
        params,
        timeout: this.timeout
      })
      return response.data
    } catch (error) {
      throw error
    }
  }

  /**
   * 用户登录
   */
  async login(phoneNumber: string, password: string, userType: string): Promise<any> {
    return await this.post('/api/auth/login', {
      phoneNumber,
      password,
      userType
    })
  }

  /**
   * 用户注册
   */
  async register(phoneNumber: string, password: string, userType: string): Promise<any> {
    return await this.post('/api/auth/register', {
      phoneNumber,
      password,
      userType
    })
  }

  /**
   * 获取餐厅列表
   */
  async getRestaurants(params?: any): Promise<any> {
    return await this.get('/api/restaurants', params)
  }

  /**
   * 获取餐厅详情
   */
  async getRestaurantDetail(restaurantId: string): Promise<any> {
    return await this.get(`/api/restaurants/${restaurantId}`)
  }

  /**
   * 获取菜品列表
   */
  async getMenu(restaurantId: string): Promise<any> {
    return await this.get(`/api/restaurants/${restaurantId}/menu`)
  }

  /**
   * 创建订单
   */
  async createOrder(orderData: any): Promise<any> {
    return await this.post('/api/orders', orderData)
  }

  /**
   * 获取订单列表
   */
  async getOrders(params?: any): Promise<any> {
    return await this.get('/api/orders', params)
  }

  /**
   * 获取订单详情
   */
  async getOrderDetail(orderId: string): Promise<any> {
    return await this.get(`/api/orders/${orderId}`)
  }

  /**
   * 更新订单状态
   */
  async updateOrderStatus(orderId: string, status: string): Promise<any> {
    return await this.put(`/api/orders/${orderId}/status`, { status })
  }

  /**
   * 获取配送订单
   */
  async getDeliveryOrders(params?: any): Promise<any> {
    return await this.get('/api/delivery/orders', params)
  }

  /**
   * 接单
   */
  async acceptOrder(orderId: string): Promise<any> {
    return await this.post(`/api/delivery/orders/${orderId}/accept`)
  }

  /**
   * 完成配送
   */
  async completeDelivery(orderId: string): Promise<any> {
    return await this.post(`/api/delivery/orders/${orderId}/complete`)
  }

  /**
   * 获取商家订单
   */
  async getMerchantOrders(params?: any): Promise<any> {
    return await this.get('/api/merchant/orders', params)
  }

  /**
   * 商家接单
   */
  async acceptMerchantOrder(orderId: string): Promise<any> {
    return await this.post(`/api/merchant/orders/${orderId}/accept`)
  }

  /**
   * 商家拒单
   */
  async rejectMerchantOrder(orderId: string, reason?: string): Promise<any> {
    return await this.post(`/api/merchant/orders/${orderId}/reject`, { reason })
  }

  /**
   * 商家完成订单
   */
  async completeMerchantOrder(orderId: string): Promise<any> {
    return await this.post(`/api/merchant/orders/${orderId}/complete`)
  }

  /**
   * 获取收入统计
   */
  async getIncomeStats(params?: any): Promise<any> {
    return await this.get('/api/stats/income', params)
  }

  /**
   * 获取营业统计
   */
  async getBusinessStats(params?: any): Promise<any> {
    return await this.get('/api/stats/business', params)
  }
}